import decimal
from matplotlib import pyplot as plt
import os
import fractions
def read_solution(filename):
   
    x=[]
    y_analytical=[]
    y_finite_element=[]
    with open(filename) as f:
        line=f.readline()
        h=float(line.split()[0].split('=')[1])
        max_error=float(line.split()[1].split('=')[1])
        for line in f.readlines()[ 1:]:
            if line == '\n':
                pass
            else:
                x.append(float(line.split()[0]))
                y_analytical.append(float(line.split()[1]))
                y_finite_element.append(float(line.split()[2]))

    return h,max_error,x,y_analytical,y_finite_element

def get_all_solutions_file(path):
    solutions_file_name=[]
    for i in os.listdir(path):
        if os.path.splitext(i)[1] == ".txt":
            solutions_file_name.append(i)
    return solutions_file_name



def main():
    fig,ax=plt.subplots(1,1)
    solutions_file=get_all_solutions_file("FE_solver_1D_Poisson")
    for file in solutions_file:

        h,max_error,x,y_ana,y_FE=read_solution(os.path.join("FE_solver_1D_Poisson",file))
        h_fract=fractions.Fraction(h)
        ax.plot(x,y_ana,label="Analytical solution")
        ax.plot(x,y_FE,ls='',marker='*',ms=10,label="FE-h={},max_error={:.5e}".format(h_fract,max_error))
        ax.set_xlabel("x")
        ax.set_ylabel("u")        
        #ax.set_title("h={},\t maximum_error={:.5e}".format(h_fract,max_error))
        ax.legend()

    plt.show()

if __name__ == "__main__":
    main()

